package fm.shop.controller;

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import fm.controller.BaseController;
import fm.exception.BizException;
import fm.shop.service.ShopService;
import fm.util.*;
import fm.web.MediaTypes;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.*;

/**
 * @修改人：CM
 * @修改时间：2017/2/28 22:30
 */
@Controller
@RequestMapping("/shopData")
public class IndexDataController extends BaseController {
    @Autowired
    ShopService shopService;

    @ResponseBody
    @RequestMapping(value = "/product/list", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map productList(ModelMap modelMap,
                           @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                           @RequestParam(required = false, defaultValue = "1") Integer pageNum) {
        Map response = new HashMap();
        try {
            Map param = getEmptyParamMap();
            param.put("uuid", getCurrentPublicNumber().getUuid());
            response.put("data", shopService.getProducts(param, pageSize, pageNum));
            this.success(response);
        } catch (Exception ex) {
            this.failed(response, ex.getMessage());
            LOGGER.error("请求数据发生错误", ex);
        }
        return response;

    }

    @ResponseBody
    @RequestMapping(value = "/product/index", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map product(ModelMap modelMap) {
        Map response = new HashMap();
        try {
            response.put("data", shopService.getIndexPros(super.getCurrentPublicNumber().getUuid()));
            this.success(response);
        } catch (Exception ex) {
            this.failed(response, ex.getMessage());
            LOGGER.error("请求数据发生错误", ex);
        }
        return response;

    }


    @ResponseBody
    @RequestMapping(value = "/purchase/list", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map purchaseList(ModelMap modelMap,
                            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                            @RequestParam(required = false, defaultValue = "1") Integer pageNum) {
        Map response = new HashMap();
        try {
            Map param = getEmptyParamMap();
//            param.put("Reply.Type","0");
            param.put("uuid", getCurrentPublicNumber().getUuid());
            response.put("data", shopService.getPurchase(param, pageSize, pageNum));
            this.success(response);
        } catch (Exception ex) {
            this.failed(response, ex.getMessage());
            LOGGER.error("请求数据发生错误", ex);
        }
        return response;
    }

    @ResponseBody
    @RequestMapping(value = "/images/{dir}/{fileName}", method = RequestMethod.GET, produces = "image/jpeg;charset=UTF-8")
    public void productList(HttpServletRequest request, HttpServletResponse response,
                            @PathVariable String dir,
                            @PathVariable String fileName) {
        try {
            fm.util.RequestHeader header = new fm.util.RequestHeader();
            header.setAccept("image/webp,image/*,*/*;q=0.8");
            header.setAcceptEncoding("gzip, deflate, sdch");
            header.setAcceptLanguage("zh-CN,zh;q=0.8");
            header.setConnection("keep-alive");
            header.setCookie("__cfduid=d4c6454d129c7e518d6a449c386a9fc7e1488074382; yjs_use_ob=0; user_lng=118.10388605; user_lat=24.48923061; Hm_lvt_6d3936097458e84313a0e6d1aa60f655=1488074383,1488119584; Hm_lpvt_6d3936097458e84313a0e6d1aa60f655=1488122314");
            header.setHost("www.2016927.com");
            header.setReferer("http://www.2016927.com/PurchaseList.aspx");
            String url = "http://www.2016927.com/images/" + dir + "/" + fileName;
//            LOGGER.info("重定向图片地址:{}", url);
            RequestUtils.redirectFile(url, response, header);
            //biz code here
        } catch (Exception ex) {
            LOGGER.error("请求数据发生错误", ex);
        }
    }

    /**
     * {
     * "Img" : "/images/Avatar/20161024111913_9200.jpg",
     * "Type" : "1",
     * "Content" : "",
     * "My" : "0",
     * "Link" : "/im.aspx?rid=8fe20fb2-d6cf-45a1-9621-c3a7e863a028",
     * "Date" : "2017-02-18 21:15:54",
     * "Name" : "晋江和文针车行"
     * }
     *
     * @param modelMap
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/pu/reply", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map likePurchase(ModelMap modelMap, String pid,
                            String type, String content) {
        Map response = new HashMap();
        try {
            Map param = getEmptyParamMap();
            param.put("uuid", getCurrentPublicNumber().getUuid());
            if (StringUtils.isEmpty(pid) || (StringUtils.isEmpty(type) && StringUtils.isEmpty(content))) {
                throw new BizException("参数缺失，回复失败");
            }

            param.put("pid", pid);
            DBObject purchase = shopService.getPurchaseUnit(param);

            if (purchase == null) {
                throw new BizException("消息已经不存在，无法回复!");
            }

            DBObject rep = new BasicDBObject("Type", type);
            if ("0".equals(type)) {
                rep.put("Content", URLDecoder.decode(content, "UTF-8"));
                if (getCurrentUser() != null && getCurrentUser().getNickname().equals(purchase.get("uname"))) {
                    rep.put("My", 1);
                } else {
                    rep.put("My", 0);
                }
            }
            rep.put("Img", getCurrentUser() == null ? "" : getCurrentUser().getHeadimgurl());
            rep.put("Date", DateUtils.formatDateTime(new Date()));
            rep.put("Name", getCurrentUser() == null ? "" : getCurrentUser().getNickname());

            BasicDBList replys = (BasicDBList) purchase.get("Reply");
            if (CollectionUtils.isEmpty(replys)) {
                replys = new BasicDBList();
                replys.add(rep);
            } else {
                if ("1".equals(type)) {
                    //取消赞
                    Iterator iterator = replys.iterator();
                    boolean exists = false;
                    while (iterator.hasNext()) {
                        DBObject rItem = (DBObject) iterator.next();
                        String name = (String) rItem.get("Name");
                        if (getCurrentUser().getNickname().equals(name)) {
                            replys.remove(rItem);
                            exists = true;
                            break;
                        }
                    }
                    if (!exists) {
                        //赞
                        replys.add(rep);
                    }
                } else {
                    replys.add(rep);
                }
            }

            DBObject update = new BasicDBObject("Reply", replys);
            shopService.updatePurchase(update, param);
            DBObject result = shopService.getPurchaseUnit(param);
            response.put("data", result);
            this.success(response);
        } catch (BizException ex) {
            this.failed(response, ex.getMessage());
            LOGGER.error("请求数据发生错误", ex);
        } catch (Exception ex) {
            this.failed(response, "服务器发生了未知错误，请稍后再试或者联系管理员解决！");
            LOGGER.error("请求数据发生错误", ex);
        }
        return response;
    }

}
